import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class LoginService extends BaseService<any> {
  private readonly logger = new Logger(LoginService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * register
   * 对应 PHP: LoginService_api::register()
   * 逻辑类型: undefined - undefined
   */
  async register(data: any) {
    // 基于PHP真实逻辑: register
    // PHP原文: //检测设置是否自动注册         //自动注册检测授权信息         //注册登录     }      /**      * 登录操作      * @param Member $member_info      * @param string $login_type      * ...
//检测设置是否自动注册
        //自动注册检测授权信息
        //注册登录
    }

    /**
     * 登录操作
     * @param Member member_info
     * @param string login_type
     * @return */
    async login(Member member_info, string login_type)
    {
        //绑定第三方授权
        this.bingOpenid(member_info);
        if (!member_info.status) throw new ApiBusinessException('MEMBER_LOCK'];
        member_info.login_time = time(];
        member_info.login_ip = this.request.ip(];
        member_info.login_channel = this.channel;
        member_info.login_type = login_type;
        member_info.login_count++;
        member_info.last_visit_time = time(];
        member_info.save(];
        const token_info = this.createToken(member_info];
        event("MemberLogin", member_info];
        return [
            token: token_info[ 'token' ],
            expires_time: token_info[ 'params' ][ 'exp' ],
            mobile: member_info.mobile
        );
    }

    /**
     * 账号登录
     * @param string username
     * @param string password
     * @return array|false
     */
    async account(string username, string password)
    {
        const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ 'username|mobile' => username, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        if (!check_password(password, member_info.password)) return false;//密码与账号不匹配
        return this.login(member_info, MemberLoginTypeDict.USERNAME);
    }

    /**
     * 手机号登录
     * @param params
     * @return */
    async mobile(params)
    {
        //校验手机验证码
        this.checkMobileCode(params[ 'mobile' )];
        //登录注册配置
        const config = ( this.memberConfigService ).getLoginConfig(];
        const is_mobile = config[ 'is_mobile' ];
        const is_bind_mobile = config[ 'is_bind_mobile' );
        if (is_mobile != 1 && is_bind_mobile != 1) throw new AuthBusinessException('MOBILE_LOGIN_UNOPENED');
        const member_service = this.memberService;

        if (!!params.openid)) {
            const mobile = params[ 'mobile' ];
            const openid = params[ 'openid' ];

            const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    app: 'wxapp_openid',
                    const default => ''
            };

            const openid_member_info = member_service.findMemberInfo([ openid_field => openid )];
            const mobile_member_info = member_service.findMemberInfo([ mobile: mobile )];

            //openid 账号已存在
            if (!openid_member_info.isEmpty()) {
                // 手机号也存在
                if (!mobile_member_info.isEmpty()) {
                    // 如果不是同一个人 抛异常
                    if (openid_member_info.member_id != mobile_member_info.member_id) {
                        throw new AuthBusinessException('MOBILE_IS_EXIST']; // 手机号已被其他账号绑定
                    }
                    // 是同一个用户，直接登录
                    return this.login(mobile_member_info, MemberLoginTypeDict.MOBILE];
                }

                // 手机号不存在，给 openid 账号绑定手机号
                openid_member_info.mobile = mobile;
                openid_member_info.save(];
                return this.login(openid_member_info, MemberLoginTypeDict.MOBILE);
            }

            //openid 账号不存在
            if (!mobile_member_info.isEmpty()) {
                // 手机号已存在，不能注册，避免重复
                throw new AuthBusinessException('MOBILE_IS_EXIST'];
            }

            //都不存在，执行注册
            const data = [
                mobile: mobile,
                nickname: params.nickname || '',
                headimg: params.headimg || '',
                const openid_field => openid
            ];
            return this.registerService.register(mobile, data, MemberRegisterTypeDict.MOBILE, false);
  }

  /**
   * login
   * 对应 PHP: LoginService_api::login()
   * 逻辑类型: undefined - undefined
   */
  async login(member_info: string, login_type: string) {
    // 基于PHP真实逻辑: login
    // PHP原文: //绑定第三方授权         $this->bingOpenid($member_info);         if (!$member_info->status) throw new ApiException('MEMBER_LOCK');         $member_info->log...
//绑定第三方授权
        this.bingOpenid(member_info);
        if (!member_info.status) throw new ApiBusinessException('MEMBER_LOCK'];
        member_info.login_time = time(];
        member_info.login_ip = this.request.ip(];
        member_info.login_channel = this.channel;
        member_info.login_type = login_type;
        member_info.login_count++;
        member_info.last_visit_time = time(];
        member_info.save(];
        const token_info = this.createToken(member_info];
        event("MemberLogin", member_info];
        return [
            token: token_info[ 'token' ],
            expires_time: token_info[ 'params' ][ 'exp' ],
            mobile: member_info.mobile
        );
    }

    /**
     * 账号登录
     * @param string username
     * @param string password
     * @return array|false
     */
    async account(string username, string password)
    {
        const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ 'username|mobile' => username, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        if (!check_password(password, member_info.password)) return false;//密码与账号不匹配
        return this.login(member_info, MemberLoginTypeDict.USERNAME);
    }

    /**
     * 手机号登录
     * @param params
     * @return */
    async mobile(params)
    {
        //校验手机验证码
        this.checkMobileCode(params[ 'mobile' )];
        //登录注册配置
        const config = ( this.memberConfigService ).getLoginConfig(];
        const is_mobile = config[ 'is_mobile' ];
        const is_bind_mobile = config[ 'is_bind_mobile' );
        if (is_mobile != 1 && is_bind_mobile != 1) throw new AuthBusinessException('MOBILE_LOGIN_UNOPENED');
        const member_service = this.memberService;

        if (!!params.openid)) {
            const mobile = params[ 'mobile' ];
            const openid = params[ 'openid' ];

            const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    app: 'wxapp_openid',
                    const default => ''
            };

            const openid_member_info = member_service.findMemberInfo([ openid_field => openid )];
            const mobile_member_info = member_service.findMemberInfo([ mobile: mobile )];

            //openid 账号已存在
            if (!openid_member_info.isEmpty()) {
                // 手机号也存在
                if (!mobile_member_info.isEmpty()) {
                    // 如果不是同一个人 抛异常
                    if (openid_member_info.member_id != mobile_member_info.member_id) {
                        throw new AuthBusinessException('MOBILE_IS_EXIST']; // 手机号已被其他账号绑定
                    }
                    // 是同一个用户，直接登录
                    return this.login(mobile_member_info, MemberLoginTypeDict.MOBILE];
                }

                // 手机号不存在，给 openid 账号绑定手机号
                openid_member_info.mobile = mobile;
                openid_member_info.save(];
                return this.login(openid_member_info, MemberLoginTypeDict.MOBILE);
            }

            //openid 账号不存在
            if (!mobile_member_info.isEmpty()) {
                // 手机号已存在，不能注册，避免重复
                throw new AuthBusinessException('MOBILE_IS_EXIST'];
            }

            //都不存在，执行注册
            const data = [
                mobile: mobile,
                nickname: params.nickname || '',
                headimg: params.headimg || '',
                const openid_field => openid
            ];
            return this.registerService.register(mobile, data, MemberRegisterTypeDict.MOBILE, false);
  }

  /**
   * account
   * 对应 PHP: LoginService_api::account()
   * 逻辑类型: undefined - undefined
   */
  async account(username: string, password: string) {
    // 基于PHP真实逻辑: account
    // PHP原文: $member_service = new MemberService();         $member_info = $member_service->findMemberInfo([ 'username|mobile' => $username, 'site_id' => $this->si...
const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ 'username|mobile' => username, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        if (!check_password(password, member_info.password)) return false;//密码与账号不匹配
        return this.login(member_info, MemberLoginTypeDict.USERNAME);
    }

    /**
     * 手机号登录
     * @param params
     * @return */
    async mobile(params)
    {
        //校验手机验证码
        this.checkMobileCode(params[ 'mobile' )];
        //登录注册配置
        const config = ( this.memberConfigService ).getLoginConfig(];
        const is_mobile = config[ 'is_mobile' ];
        const is_bind_mobile = config[ 'is_bind_mobile' );
        if (is_mobile != 1 && is_bind_mobile != 1) throw new AuthBusinessException('MOBILE_LOGIN_UNOPENED');
        const member_service = this.memberService;

        if (!!params.openid)) {
            const mobile = params[ 'mobile' ];
            const openid = params[ 'openid' ];

            const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    app: 'wxapp_openid',
                    const default => ''
            };

            const openid_member_info = member_service.findMemberInfo([ openid_field => openid )];
            const mobile_member_info = member_service.findMemberInfo([ mobile: mobile )];

            //openid 账号已存在
            if (!openid_member_info.isEmpty()) {
                // 手机号也存在
                if (!mobile_member_info.isEmpty()) {
                    // 如果不是同一个人 抛异常
                    if (openid_member_info.member_id != mobile_member_info.member_id) {
                        throw new AuthBusinessException('MOBILE_IS_EXIST']; // 手机号已被其他账号绑定
                    }
                    // 是同一个用户，直接登录
                    return this.login(mobile_member_info, MemberLoginTypeDict.MOBILE];
                }

                // 手机号不存在，给 openid 账号绑定手机号
                openid_member_info.mobile = mobile;
                openid_member_info.save(];
                return this.login(openid_member_info, MemberLoginTypeDict.MOBILE);
            }

            //openid 账号不存在
            if (!mobile_member_info.isEmpty()) {
                // 手机号已存在，不能注册，避免重复
                throw new AuthBusinessException('MOBILE_IS_EXIST'];
            }

            //都不存在，执行注册
            const data = [
                mobile: mobile,
                nickname: params.nickname || '',
                headimg: params.headimg || '',
                const openid_field => openid
            ];
            return this.registerService.register(mobile, data, MemberRegisterTypeDict.MOBILE, false);
  }

  /**
   * mobile
   * 对应 PHP: LoginService_api::mobile()
   * 逻辑类型: undefined - undefined
   */
  async mobile(params: any) {
    // 基于PHP真实逻辑: mobile
    // PHP原文: //校验手机验证码         $this->checkMobileCode($params[ 'mobile' ]);         //登录注册配置         $config = ( new MemberConfigService() )->getLoginConfig();    ...
//校验手机验证码
        this.checkMobileCode(params[ 'mobile' )];
        //登录注册配置
        const config = ( this.memberConfigService ).getLoginConfig(];
        const is_mobile = config[ 'is_mobile' ];
        const is_bind_mobile = config[ 'is_bind_mobile' );
        if (is_mobile != 1 && is_bind_mobile != 1) throw new AuthBusinessException('MOBILE_LOGIN_UNOPENED');
        const member_service = this.memberService;

        if (!!params.openid)) {
            const mobile = params[ 'mobile' ];
            const openid = params[ 'openid' ];

            const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    app: 'wxapp_openid',
                    const default => ''
            };

            const openid_member_info = member_service.findMemberInfo([ openid_field => openid )];
            const mobile_member_info = member_service.findMemberInfo([ mobile: mobile )];

            //openid 账号已存在
            if (!openid_member_info.isEmpty()) {
                // 手机号也存在
                if (!mobile_member_info.isEmpty()) {
                    // 如果不是同一个人 抛异常
                    if (openid_member_info.member_id != mobile_member_info.member_id) {
                        throw new AuthBusinessException('MOBILE_IS_EXIST']; // 手机号已被其他账号绑定
                    }
                    // 是同一个用户，直接登录
                    return this.login(mobile_member_info, MemberLoginTypeDict.MOBILE];
                }

                // 手机号不存在，给 openid 账号绑定手机号
                openid_member_info.mobile = mobile;
                openid_member_info.save(];
                return this.login(openid_member_info, MemberLoginTypeDict.MOBILE);
            }

            //openid 账号不存在
            if (!mobile_member_info.isEmpty()) {
                // 手机号已存在，不能注册，避免重复
                throw new AuthBusinessException('MOBILE_IS_EXIST'];
            }

            //都不存在，执行注册
            const data = [
                mobile: mobile,
                nickname: params.nickname || '',
                headimg: params.headimg || '',
                const openid_field => openid
            ];
            return this.registerService.register(mobile, data, MemberRegisterTypeDict.MOBILE, false);
  }

  /**
   * createToken
   * 对应 PHP: LoginService_api::createToken()
   * 逻辑类型: undefined - undefined
   */
  async createToken(member_info: any) {
    // 基于PHP真实逻辑: createToken
    // PHP原文: $expire_time = env('system.api_token_expire_time') ?? 3600;//todo  不一定和管理端合用这个token时限         return TokenAuth::createToken($member_info->member_id, A...
const expire_time = env('system.api_token_expire_time') || 3600;//todo  不一定和管理端合用这个token时限
        return TokenAuth.createToken(member_info.member_id, AppTypeDict.API, [ member_id: member_info.member_id, username: member_info.username, site_id: member_info.site_id ), expire_time];
    }

    /**
     * 登陆退出(当前账户)
     */
    async logout() : ?bool
    {
        self.clearToken(this.member_id, this.request.apiToken()];
        return true;
    }

    /**
     * 清理token
     * @param int member_id
     * @param string|null token
     * @return bool|null
     */
    public static function clearToken(int member_id, ?string token = '') : ?bool
    {
        TokenAuth.clearToken(member_id, AppTypeDict.API, token);
        return true;
    }

    /**
     * 解析token
     * @param string|null token
     * @return */
    async parseToken(?string token)
    {
        if (!token)) {
            //定义专属于授权认证机制的错误响应, 定义专属语言包
            throw new AuthBusinessException('MUST_LOGIN', 401);
  }

  /**
   * logout
   * 对应 PHP: LoginService_api::logout()
   * 逻辑类型: undefined - undefined
   */
  async logout() {
    // 基于PHP真实逻辑: logout
    // PHP原文: self::clearToken($this->member_id, $this->request->apiToken());         return true;     }      /**      * 清理token      * @param int $member_id      *...
self.clearToken(this.member_id, this.request.apiToken()];
        return true;
    }

    /**
     * 清理token
     * @param int member_id
     * @param string|null token
     * @return bool|null
     */
    public static function clearToken(int member_id, ?string token = '') : ?bool
    {
        TokenAuth.clearToken(member_id, AppTypeDict.API, token);
        return true;
    }

    /**
     * 解析token
     * @param string|null token
     * @return */
    async parseToken(?string token)
    {
        if (!token)) {
            //定义专属于授权认证机制的错误响应, 定义专属语言包
            throw new AuthBusinessException('MUST_LOGIN', 401);
  }

  /**
   * clearToken
   * 对应 PHP: LoginService_api::clearToken()
   * 逻辑类型: undefined - undefined
   */
  async clearToken(member_id: number, token: number) {
    // 基于PHP真实逻辑: clearToken
    // PHP原文: TokenAuth::clearToken($member_id, AppTypeDict::API, $token);         return true;     }      /**      * 解析token      * @param string|null $token      ...
TokenAuth.clearToken(member_id, AppTypeDict.API, token);
        return true;
    }

    /**
     * 解析token
     * @param string|null token
     * @return */
    async parseToken(?string token)
    {
        if (!token)) {
            //定义专属于授权认证机制的错误响应, 定义专属语言包
            throw new AuthBusinessException('MUST_LOGIN', 401);
  }

  /**
   * parseToken
   * 对应 PHP: LoginService_api::parseToken()
   * 逻辑类型: undefined - undefined
   */
  async parseToken(token: string) {
    // 基于PHP真实逻辑: parseToken
    // PHP原文: if (empty($token)) {             //定义专属于授权认证机制的错误响应, 定义专属语言包             throw new AuthException('MUST_LOGIN', 401);...
if (!token)) {
            //定义专属于授权认证机制的错误响应, 定义专属语言包
            throw new AuthBusinessException('MUST_LOGIN', 401);
  }

  /**
   * sendMobileCode
   * 对应 PHP: LoginService_api::sendMobileCode()
   * 逻辑类型: undefined - undefined
   */
  async sendMobileCode(mobile: string, type: string) {
    // 基于PHP真实逻辑: sendMobileCode
    // PHP原文: ( new CaptchaService() )->check();         if (empty($mobile)) throw new AuthException('MOBILE_NEEDED');         //发送         if (!in_array($type, Sms...
( this.captchaService ).check(];
        if (!mobile)) throw new AuthBusinessException('MOBILE_NEEDED');
        //发送
        if (!in_[type, SmsDict.SCENE_TYPE)) throw new AuthBusinessException('MEMBER_MOBILE_CAPTCHA_ERROR');
        const code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT];// 生成4位随机数，左侧补0
        ( this.noticeService ).send('member_verify_code', [ code: code, mobile: mobile )];
        //将验证码存入缓存
        const key = md5(uniqid('', true)];
        const cache_tag_name = "mobile_key" . mobile . type;
        this.clearMobileCode(mobile, type);
        Cache.tag(cache_tag_name).set(key, [ mobile: mobile, code: code, type: type ), 600];
        return [ key: key ];
    }

    async getMobileCodeCacheName()
    {
    // 待实现
  }

    async clearMobileCode(mobile, type)
    {
        const cache_tag_name = "mobile_key" . mobile . type;
        Cache.tag(cache_tag_name).clear(];
    }

    /**
     * 校验手机验证码
     * @param string mobile
     * @return true
     */
    async checkMobileCode(string mobile)
    {
        if (!mobile)) throw new AuthBusinessException('MOBILE_NEEDED');
        const mobile_key = request().param('mobile_key', '');
        const mobile_code = request().param('mobile_code', '');
        if (!mobile_key) || !mobile_code)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const cache = Cache.get(mobile_key);
        if (!cache)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const temp_mobile = cache[ 'mobile' ];
        const temp_code = cache[ 'code' ];
        const temp_type = cache[ 'type' );
        if (temp_mobile != mobile || temp_code != mobile_code) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        this.clearMobileCode(temp_mobile, temp_type);
        return true;

    }

    /**
     * 绑定openid
     * @param member
     * @return true
     */
    async bingOpenid(member)
    {
        const open_id = this.request.param('openid');
        if (!!open_id)) {
            Log.write('channel_1' . this.channel);
            if (!!this.channel)) {
                const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    const default => ''
                };
                if (!!openid_field)) {
                    if (!member.isEmpty()) {
                        if (!member.openid_field)) {
                            const member_service = this.memberService;
                            const open_member = member_service.findMemberInfo([ openid_field => open_id, site_id: this.site_id )];
                            // 检测openid是否存在账号验证
                            if (!open_member)) {
                                member.openid_field = open_id;
                                member.save(];
                            }
                        } } } else {
                            if (member.openid_field != open_id) {
                                throw new AuthBusinessException('MEMBER_IS_BIND_AUTH');
                            }
                        }
                    }
                }
            }
  }

  /**
   * getMobileCodeCacheName
   * 对应 PHP: LoginService_api::getMobileCodeCacheName()
   * 逻辑类型: undefined - undefined
   */
  async getMobileCodeCacheName() {
    // 基于PHP真实逻辑: getMobileCodeCacheName
    // PHP原文: }      public function clearMobileCode($mobile, $type)     {         $cache_tag_name = "mobile_key" . $mobile . $type;         Cache::tag($cache_tag_n...
}

    async clearMobileCode(mobile, type)
    {
        const cache_tag_name = "mobile_key" . mobile . type;
        Cache.tag(cache_tag_name).clear(];
    }

    /**
     * 校验手机验证码
     * @param string mobile
     * @return true
     */
    async checkMobileCode(string mobile)
    {
        if (!mobile)) throw new AuthBusinessException('MOBILE_NEEDED');
        const mobile_key = request().param('mobile_key', '');
        const mobile_code = request().param('mobile_code', '');
        if (!mobile_key) || !mobile_code)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const cache = Cache.get(mobile_key);
        if (!cache)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const temp_mobile = cache[ 'mobile' ];
        const temp_code = cache[ 'code' ];
        const temp_type = cache[ 'type' );
        if (temp_mobile != mobile || temp_code != mobile_code) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        this.clearMobileCode(temp_mobile, temp_type);
        return true;

    }

    /**
     * 绑定openid
     * @param member
     * @return true
     */
    async bingOpenid(member)
    {
        const open_id = this.request.param('openid');
        if (!!open_id)) {
            Log.write('channel_1' . this.channel);
            if (!!this.channel)) {
                const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    const default => ''
                };
                if (!!openid_field)) {
                    if (!member.isEmpty()) {
                        if (!member.openid_field)) {
                            const member_service = this.memberService;
                            const open_member = member_service.findMemberInfo([ openid_field => open_id, site_id: this.site_id )];
                            // 检测openid是否存在账号验证
                            if (!open_member)) {
                                member.openid_field = open_id;
                                member.save(];
                            }
                        } } } else {
                            if (member.openid_field != open_id) {
                                throw new AuthBusinessException('MEMBER_IS_BIND_AUTH');
                            }
                        }
                    }
                }
            }
  }

  /**
   * clearMobileCode
   * 对应 PHP: LoginService_api::clearMobileCode()
   * 逻辑类型: undefined - undefined
   */
  async clearMobileCode(mobile: any, type: any) {
    // 基于PHP真实逻辑: clearMobileCode
    // PHP原文: $cache_tag_name = "mobile_key" . $mobile . $type;         Cache::tag($cache_tag_name)->clear();     }      /**      * 校验手机验证码      * @param string $mo...
const cache_tag_name = "mobile_key" . mobile . type;
        Cache.tag(cache_tag_name).clear(];
    }

    /**
     * 校验手机验证码
     * @param string mobile
     * @return true
     */
    async checkMobileCode(string mobile)
    {
        if (!mobile)) throw new AuthBusinessException('MOBILE_NEEDED');
        const mobile_key = request().param('mobile_key', '');
        const mobile_code = request().param('mobile_code', '');
        if (!mobile_key) || !mobile_code)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const cache = Cache.get(mobile_key);
        if (!cache)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const temp_mobile = cache[ 'mobile' ];
        const temp_code = cache[ 'code' ];
        const temp_type = cache[ 'type' );
        if (temp_mobile != mobile || temp_code != mobile_code) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        this.clearMobileCode(temp_mobile, temp_type);
        return true;

    }

    /**
     * 绑定openid
     * @param member
     * @return true
     */
    async bingOpenid(member)
    {
        const open_id = this.request.param('openid');
        if (!!open_id)) {
            Log.write('channel_1' . this.channel);
            if (!!this.channel)) {
                const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    const default => ''
                };
                if (!!openid_field)) {
                    if (!member.isEmpty()) {
                        if (!member.openid_field)) {
                            const member_service = this.memberService;
                            const open_member = member_service.findMemberInfo([ openid_field => open_id, site_id: this.site_id )];
                            // 检测openid是否存在账号验证
                            if (!open_member)) {
                                member.openid_field = open_id;
                                member.save(];
                            }
                        } } } else {
                            if (member.openid_field != open_id) {
                                throw new AuthBusinessException('MEMBER_IS_BIND_AUTH');
                            }
                        }
                    }
                }
            }
  }

  /**
   * checkMobileCode
   * 对应 PHP: LoginService_api::checkMobileCode()
   * 逻辑类型: undefined - undefined
   */
  async checkMobileCode(mobile: string) {
    // 基于PHP真实逻辑: checkMobileCode
    // PHP原文: if (empty($mobile)) throw new AuthException('MOBILE_NEEDED');         $mobile_key = request()->param('mobile_key', '');         $mobile_code = request...
if (!mobile)) throw new AuthBusinessException('MOBILE_NEEDED');
        const mobile_key = request().param('mobile_key', '');
        const mobile_code = request().param('mobile_code', '');
        if (!mobile_key) || !mobile_code)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const cache = Cache.get(mobile_key);
        if (!cache)) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        const temp_mobile = cache[ 'mobile' ];
        const temp_code = cache[ 'code' ];
        const temp_type = cache[ 'type' );
        if (temp_mobile != mobile || temp_code != mobile_code) throw new AuthBusinessException('MOBILE_CAPTCHA_ERROR'];
        this.clearMobileCode(temp_mobile, temp_type);
        return true;

    }

    /**
     * 绑定openid
     * @param member
     * @return true
     */
    async bingOpenid(member)
    {
        const open_id = this.request.param('openid');
        if (!!open_id)) {
            Log.write('channel_1' . this.channel);
            if (!!this.channel)) {
                const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    const default => ''
                };
                if (!!openid_field)) {
                    if (!member.isEmpty()) {
                        if (!member.openid_field)) {
                            const member_service = this.memberService;
                            const open_member = member_service.findMemberInfo([ openid_field => open_id, site_id: this.site_id )];
                            // 检测openid是否存在账号验证
                            if (!open_member)) {
                                member.openid_field = open_id;
                                member.save(];
                            }
                        } } } else {
                            if (member.openid_field != open_id) {
                                throw new AuthBusinessException('MEMBER_IS_BIND_AUTH');
                            }
                        }
                    }
                }
            }
  }

  /**
   * bingOpenid
   * 对应 PHP: LoginService_api::bingOpenid()
   * 逻辑类型: undefined - undefined
   */
  async bingOpenid(member: any) {
    // 基于PHP真实逻辑: bingOpenid
    // PHP原文: $open_id = $this->request->param('openid');         if (!empty($open_id)) {             Log::write('channel_1' . $this->channel);             if (!emp...
const open_id = this.request.param('openid');
        if (!!open_id)) {
            Log.write('channel_1' . this.channel);
            if (!!this.channel)) {
                const openid_field = match ( this.channel ) {
                    wechat: 'wx_openid',
                    weapp: 'weapp_openid',
                    const default => ''
                };
                if (!!openid_field)) {
                    if (!member.isEmpty()) {
                        if (!member.openid_field)) {
                            const member_service = this.memberService;
                            const open_member = member_service.findMemberInfo([ openid_field => open_id, site_id: this.site_id )];
                            // 检测openid是否存在账号验证
                            if (!open_member)) {
                                member.openid_field = open_id;
                                member.save(];
                            }
                        } } } else {
                            if (member.openid_field != open_id) {
                                throw new AuthBusinessException('MEMBER_IS_BIND_AUTH');
                            }
                        }
                    }
                }
            }
  }

  /**
   * resetPassword
   * 对应 PHP: LoginService_api::resetPassword()
   * 逻辑类型: undefined - undefined
   */
  async resetPassword(mobile: string, password: string) {
    // 基于PHP真实逻辑: resetPassword
    // PHP原文: $member_service = new MemberService();         //校验手机验证码         $this->checkMobileCode($mobile);         $member_info = $member_service->findMemberIn...
const member_service = this.memberService;
        //校验手机验证码
        this.checkMobileCode(mobile);
        const member_info = member_service.findMemberInfo([ mobile: mobile, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MOBILE_NOT_EXIST_MEMBER'];//账号不存在
        //todo  需要考虑一下,新的密码和原密码一样能否通过验证
        const password_hash = create_password(password];
        const data = [
            password: password_hash,
        ];
        member_service.editByFind(member_info, data);
        self.clearToken(member_info[ 'member_id' ), this.request.apiToken()];
        return true;
    }

    async loginScanCode()
    {
    // 待实现
  }

    async loginByScanCode()
    {
    // 待实现
  }

    async checkScanCode()
    {
    // 待实现
  }

}
  }

  /**
   * loginScanCode
   * 对应 PHP: LoginService_api::loginScanCode()
   * 逻辑类型: undefined - undefined
   */
  async loginScanCode() {
    // 基于PHP真实逻辑: loginScanCode
    // PHP原文: }      public function loginByScanCode()     {      }      public function checkScanCode()     {      }  }...
}

    async loginByScanCode()
    {
    // 待实现
  }

    async checkScanCode()
    {
    // 待实现
  }

}
  }

  /**
   * loginByScanCode
   * 对应 PHP: LoginService_api::loginByScanCode()
   * 逻辑类型: undefined - undefined
   */
  async loginByScanCode() {
    // 基于PHP真实逻辑: loginByScanCode
    // PHP原文: }      public function checkScanCode()     {      }  }...
}

    async checkScanCode()
    {
    // 待实现
  }

}
  }
}
